package ki;

import javax.imageio.metadata.IIOMetadataNode;

import org.w3c.dom.Node;

public class NimDecisionTree {
	private final int maxRemove; //maximum number of stick that can be removed from the pile
	
	
	public NimDecisionTree(int maxRemove) {
		this.maxRemove = maxRemove;
		
	}
	
	//build the decision tree
	public Node buildDecisionTree(int numberOfSticks) {
		//create root node. value is the number of sticks
		Node rootNode = new IIOMetadataNode();
		rootNode.setNodeValue(String.valueOf(numberOfSticks));
		this.buildSubTreeRecusive(rootNode);
		
		return rootNode;
		
	}
	
	//build subtrees of the decision tree recursive
	private void buildSubTreeRecusive(Node node) {
		int currentSticksLeft = Integer.parseInt(node.getNodeValue());

		//if currentSticks are more then zero create the subtree. if there is no stick left there is no need to create the subtree
		if (currentSticksLeft > 0) {
			for (int i = 1; i <= this.getMaxSticksToRemove(currentSticksLeft); i++) {
				Node child = new IIOMetadataNode();
				child.setNodeValue(String.valueOf(currentSticksLeft - i));
				node.appendChild(child);
				
				this.buildSubTreeRecusive(child);
			} 
		}
		
	}

	//get the max number of sticks to remove (e.g. currentSticksLeft or maxRemove)
	private int getMaxSticksToRemove(int currentSticksLeft) {
		if (currentSticksLeft < this.maxRemove) 
			return currentSticksLeft;
		else return this.maxRemove;
		
	}
	
	//returns true if the given value is a win situation
	public int isWinningSituation(int value) {
		if (((value % (this.maxRemove + 1))  == 0 || (value == 0))) 
			return 1;
		else return -1;
		
	}

	public int getMaxRemove() {
		return maxRemove;
	}
}
